package org.phoenixframework.common.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.phoenixframework.common.security.config.TokenManager;
import org.phoenixframework.common.security.entity.PhoenixSecurityUser;
import org.phoenixframework.common.tools.Constants;
import org.phoenixframework.common.tools.ResponseUtil;
import org.phoenixframework.common.tools.ResultModel;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2021/5/6 22:03
 * Description:
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    private final TokenManager tokenManager;

    private final RedisTemplate redisTemplate;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/security/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
        try {
            PhoenixSecurityUser user = new ObjectMapper().readValue(req.getInputStream(), PhoenixSecurityUser.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException {
        PhoenixSecurityUser user = (PhoenixSecurityUser) auth.getPrincipal();
        Map<String, Object> claims = new HashMap<>(8);
        claims.put(Constants.USERNAME, user.getUsername());
        claims.put(Constants.USER_ID, user.getId());
        String token = tokenManager.createToken(claims);
        redisTemplate.opsForValue().set(user.getUsername(), user.getAuthorities());
        ResponseUtil.out(res, ResultModel.map("token", token));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, ResultModel.error("unsuccessfulAuthentication"));
    }
}

